package com.sxfq.loansupermarket.backsystem.modular.theTest.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.theTest.service.ITestingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取生成的考试题列表
 *
 * @author py
 * @Date 2018年2月4日23:05:54
 */
@Controller
@RequestMapping("/getTestGenerate")
public class GetTestGenerateController extends BaseController {

    @Autowired
    ITestingService iTestingService;

    @Autowired
    private SqlMapper sqlMapper;

    /**
     * 获得生成的考试提列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(SearchTestingInfo query) throws Exception {
        Page<TestQuestionsInfo> page = new PageFactory<TestQuestionsInfo>().defaultPage();
        try {
            query.setTheTestId(ShiroKit.getSessionAttr("theTestId"));
            query.setUserId(ShiroKit.getUser().getId().toString());
            List<TestQuestionsInfo> testQuestionsInfoList = iTestingService.selectPageListByQueryGetMap(page, query);
            page.setRecords(testQuestionsInfoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 正式考试没做的题目
     */
    @RequestMapping(value = "/getNullTitle")
    @ResponseBody
    public List getNullTitle(@Valid SearchTestingInfo query, BindingResult result) throws Exception {
        String sql = "select * from the_test_info a where a.the_test_name='咿呀正式考试'";
        TheTestInfo theTestInfos = sqlMapper.selectOne(sql, TheTestInfo.class);
        String sql1 = "select test_number from user_for_test_info" +
                " t where t.user_id=" + ShiroKit.getUser().getId() + " and t.the_test_id='" + theTestInfos.getId() + "' and t.user_answer is null order by test_number asc";
        List<UserForTestInfo> getNullTitle = sqlMapper.selectList(sql1, UserForTestInfo.class);
        List list=new ArrayList();
        for(UserForTestInfo info:getNullTitle){
            list.add(info.getTestNumber());
        }
        return list;
    }
    /**
     * 模拟考试没做的题目
     */
    @RequestMapping(value = "/getMoniNullTitle")
    @ResponseBody
    public List getMoniNullTitle(@Valid SearchTestingInfo query, BindingResult result) throws Exception {
        String sql = "select * from the_test_info a where a.the_test_name='咿呀模拟考试'";
        TheTestInfo theTestInfos = sqlMapper.selectOne(sql, TheTestInfo.class);
        String sql1 = "select test_number from user_for_test_info" +
                " t where t.user_id=" + ShiroKit.getUser().getId() + " and t.the_test_id='" + theTestInfos.getId() + "' and t.user_answer is null order by test_number asc";
        List<UserForTestInfo> getNullTitle = sqlMapper.selectList(sql1, UserForTestInfo.class);
        List list=new ArrayList();
        for(UserForTestInfo info:getNullTitle){
            list.add(info.getTestNumber());
        }
        return list;
    }
    /**
     * 正式考试交卷
     */
    @RequestMapping(value = "/handOverAnswei")
    @ResponseBody
    public String getScore(@Valid SearchTestingInfo query, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select * from the_test_info a where a.the_test_name='咿呀正式考试'";
        TheTestInfo theTestInfos = sqlMapper.selectOne(sql, TheTestInfo.class);
        List<UserForTestInfo> testGetScoreInfoList = iTestingService.selectPageListgetScore(theTestInfos.getId(), query.getUserId());
        if (testGetScoreInfoList.size() == 0) {
            return REDIRECT + "/testMenu";
        } else {
            Double testScores = 0.00;

            for (UserForTestInfo info : testGetScoreInfoList) {
                if (info.getCorrectAnswer().equals(info.getUserAnswer())) {
                    testScores += info.getScoresOfQuestion();
                } else {
                    String sql3 = "insert into error_questions_info (id,user_id,test_questions_id)  values";
                    sql3 += "('" + CommUtils.getUUID() + "'," + ShiroKit.getUser().getId() + ",'" + info.getTestQuestionsId() + "');";
                    sqlMapper.insert(sql3);
                }
            }

            String sql1 = "select  a.the_test_score  from user a where a.id=" + ShiroKit.getUser().getId() + " ";
            UserDto userDto = sqlMapper.selectOne(sql1, UserDto.class);
            if (testScores >= userDto.getTheTestScore()) {
                iTestingService.changeScore(ShiroKit.getUser().getId(), testScores);
            }
            String sql2 = "delete from user_for_test_info  where user_id=" + ShiroKit.getUser().getId() + " and the_test_id='" + theTestInfos.getId() + "' ";
            String sql4 = "delete from error_questions_info  where  user_id=" + ShiroKit.getUser().getId() + " and test_questions_id in  ( " +
                    "  select t.test_questions_id from  " +
                    "  ( " +
                    "  select t1.test_questions_id from error_questions_info t1 where  user_id=" + ShiroKit.getUser().getId() + " group by t1.test_questions_id having count(t1.test_questions_id) > 1  " +
                    " ) t ) " +
                    "and id not in ( " +
                    "  select t3.id from  " +
                    "  ( " +
                    " (select min(t2.id) as id from error_questions_info t2 where  user_id=" + ShiroKit.getUser().getId() + " group by t2.test_questions_id     having count(t2.id)>1)  " +
                    " ) t3  )";
            sqlMapper.delete(sql4);
            sqlMapper.delete(sql2);
            ShiroKit.setSessionAttr("testScores", testScores);
            return testScores.toString();
        }
    }

    /**
     * 正式考试交卷
     */
    @RequestMapping(value = "/handOverMoni")
    @ResponseBody
    public String getScores(@Valid SearchTestingInfo query, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select * from the_test_info a where a.the_test_name='咿呀模拟考试'";
        TheTestInfo theTestInfos = sqlMapper.selectOne(sql, TheTestInfo.class);
        List<UserForTestInfo> testGetScoreInfoList = iTestingService.selectPageListgetScore(theTestInfos.getId(), query.getUserId());
        if (testGetScoreInfoList.size() == 0) {
            return REDIRECT + "/testMenu";
        } else {
            Double testScores = 0.00;
            for (UserForTestInfo info : testGetScoreInfoList) {
                if (info.getCorrectAnswer().equals(info.getUserAnswer())) {
                    testScores += info.getScoresOfQuestion();
                } else {
                    String sql3 = "insert into error_questions_info (id,user_id,test_questions_id)  values";
                    sql3 += "('" + CommUtils.getUUID() + "'," + ShiroKit.getUser().getId() + ",'" + info.getTestQuestionsId() + "');";
                    sqlMapper.insert(sql3);
                }
            }
            String sql4 = "delete from error_questions_info  where  user_id=" + ShiroKit.getUser().getId() + " and test_questions_id in  ( " +
                    "  select t.test_questions_id from  " +
                    "  ( " +
                    "  select t1.test_questions_id from error_questions_info t1 where  user_id=" + ShiroKit.getUser().getId() + " group by t1.test_questions_id having count(t1.test_questions_id) > 1  " +
                    " ) t ) " +
                    "and id not in ( " +
                    "  select t3.id from  " +
                    "  ( " +
                    " (select min(t2.id) as id from error_questions_info t2 where  user_id=" + ShiroKit.getUser().getId() + " group by t2.test_questions_id     having count(t2.id)>1)  " +
                    " ) t3  )";
            String sql2 = "delete from user_for_test_info  where user_id=" + ShiroKit.getUser().getId() + " and the_test_id='" + theTestInfos.getId() + "'";
            sqlMapper.delete(sql2);
            sqlMapper.delete(sql4);
            ShiroKit.setSessionAttr("testScores", testScores);
            return testScores.toString();
        }
    }
}
